package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * TODO
 *
 * @Author mr.du
 * @Date2024/12/9 14:23
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 执行插入的拦截
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {

        this.strictInsertFill(metaObject,"createTime",Date.class,new Date());
        this.strictInsertFill(metaObject,"createBy",String.class,String.valueOf(loadUserId()));
    }


    /**
     * 执行修改的拦截
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {

        this.strictUpdateFill(metaObject,"updateTime",Date.class,new Date());
        this.strictUpdateFill(metaObject,"updateBy",String.class,String.valueOf(loadUserId()));
    }

    /**
     * 获取当前登录人的ID
     * @return  登录人ID
     */
    public Long loadUserId() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser != null) {
            return loginUser.getUserId();
        }
        return 1L;
    }
}
